<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
    <title>Student Website</title>
</head>

<body>
    <div class="navbar">
        <span class="title"><a href="/" style="text-decoration: none;color: black">Back To Main Page</a></span>
    </div>

    <div class="card">
        <a onclick="window.history.go(-1)">Back</a>
        <h2>
            Create a new Homework
        </h2>
        <p>Name</p>
        <input type="text" name="name" id="hw_name" class="input">
        <p>Homework requirements</p>
        <textarea type="text" name="class_name" id="hw_request" class="input"></textarea>
        <p>Class name</p>
        <input type="text" name="class_name" id="class_name" class="input">
        <p>Begin time</p>
        <input type="datetime-local" name="begintime" id="begintime" class="input">
        <p>Over time</p>
        <input type="datetime-local" name="overtime" id="overtime" class="input">
        <br>
        <button onclick="newCoures()" class="button" style="margin-top: 15px;">Create</button>
    </div>
</body>

<script>
    const urlParams = new URLSearchParams(window.location.search);
    const _classname = urlParams.get('classname');

    document.getElementById("class_name").value = _classname;
</script>

<script>
    function newCoures() {
        const homeworkname = document.getElementById("hw_name").value;
        const classname = document.getElementById("class_name").value;
        const descriptive = document.getElementById("hw_request").value;
        const begintime = document.getElementById("begintime").value;
        const overtime = document.getElementById("overtime").value;

        fetch('/api/homeworks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                homeworkname: homeworkname,
                classname: classname,
                descriptive: descriptive,
                begintime: begintime,
                overtime: overtime
            })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to post class');
                }
                alert("Creating Homework Success!");
                return response.json();
            })
            .then(data => {
                window.location.href = `/class?classname=${classname}`;
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
</script>

</html>